#include <stdio.h> 
#include <memory.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

long file_size(const char* file_name)
{
    struct stat file_stat;
    if(stat(file_name, &file_stat) == -1) {
        printf("[%s] stat file : %s:  %s \n", __func__, file_name , strerror(errno));
        return -1;
    }
    return file_stat.st_size;
}

/**
* 如果content不为空，调用该函数后，需要在调用方释放free(*content)
*/
long file_content(const char* file_name, char** content)
{
    // opening the file in read mode 
    FILE* fp;
#ifdef _WIN32
    fopen_s(&fp, file_name, "rb");
#else
    fp = fopen(file_name, "rb");
#endif

    // checking if the file exist or not 
    if (fp == NULL) {
        printf("File Not Found!\n");
        return -1;
    }

    fseek(fp, 0L, SEEK_END);

    // calculating the size of the file 
    long int res = ftell(fp);

    if (content)
    {
        /* reset the file position indicator to the beginning of the file */
        fseek(fp, 0L, SEEK_SET);
        char* buf = (char*)malloc(res * sizeof(char));
        if (!buf)
        {
            fclose(fp);
            return -2;
        }
        if (fread(buf, sizeof(char), res, fp) != res)
        {
            fclose(fp);
            free(buf);
            return -3;
        }
        *content = buf;
    }

    // closing the file 
    fclose(fp);
    return res;
}

int main()
{
    char* content = NULL;
    long len = file_content("./file.c", &content);
    if (len < 0)
    {
        printf("file_content faild\n");
        return -1;
    }
    printf("len = %d\n", len);
    printf("content = %s\n", content);

    return 0;
}
